const fs = require('fs');
const resolve = require('url').resolve;

class ProjectService {
  async createProject(options) {
    console.log(__dirname);
    console.log(resolve(__dirname, '../'));
  }

  async getProjectPages(project) {
    const projectPath = resolve(__dirname, `../workspace/${project}/src/pages`);
    const files = await fs.readdirSync(projectPath);
    return files;
  }
  
  /**
   * 查询页面配置信息
   * @param project 项目名称
   * @param page 页面路径
   * @returns json
   */
  async getPageConfig(project, page) {
    const pageConfigPath = resolve(__dirname, `../workspace/${project}/src/pages/${page}/index.page.json`);
    const json = fs.readFileSync(pageConfigPath, 'utf-8');
    return JSON.parse(json);
  }

  async getCode(project, page) {
    const pageCodePath = resolve(__dirname, `../workspace/${project}/src/pages/${page}/Scope.ts`);
    const code = fs.readFileSync(pageCodePath, 'utf-8');
    return code;
  }

  async asyncConfig({ project, page, pageConfig }) {
    const pageConfigPath = resolve(__dirname, `../workspace/${project}/src/pages/${page}/index.page.json`);
    try {
      const json = fs.writeFileSync(pageConfigPath, JSON.stringify(pageConfig), 'utf-8');
      console.log('json: ', pageConfig);
      return {
        success: true,
        errorMgs: '',
        errorCode: 200,
        data: pageConfig
      }
    } catch (error) {
      return {
        success: false,
        errorMgs: error
      }
    }

  }
  
  asyncCode({ project, page, code }) {
    console.log('进来啦');
    console.log('-->', project, page, code);
    const pageConfigPath = resolve(__dirname, `../workspace/${project}/src/pages/${page}/Scope.ts`);
    let res;
    try {
      const json = fs.writeFileSync(pageConfigPath, code, 'utf-8');
      res = {
        success: true,
        errorMgs: '',
        errorCode: 200,
        data: ''
      }
    } catch (error) {
      res = {
        success: false,
        errorMgs: error
      }
    }
    return res;
  }
}

module.exports = new ProjectService;